package com.zxy.salenet.web.service;

import com.zxy.salenet.web.mapper.SalenetCarMapper;
import com.zxy.salenet.web.mapper.SalenetUserMapper;
import com.zxy.salenet.web.pojo.SalenetCar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: zxy
 * @version: 1.0
 * @description:
 */
   /**
 * LoadCarData:
 */
@Service
public class LoadCarData {
    @Autowired
    private SalenetUserMapper userMapper;
    @Autowired
    private SalenetCarMapper carMapper;

    /**
     * 创建购物车map集合
     */
    public static Map<Integer, List<SalenetCar>> carMap = new HashMap<>();

    /**
     * 项目启动初始化数据
     *
     */
    @PostConstruct
//    @Scheduled(fixedRate = 2000)
    public void init() {
        System.out.println("项目启动中...正在加载数据,启动时加载数据库中的购物车数据...");
        //给map集合添加数据
        //先获取所有的用户
        List<Integer> userIdList = userMapper.selectAllUserId();
        //根据用户id获取对应用户在购物车中的数据
        for(Integer userId : userIdList){
            //循环获取数据然后添加到map中
            List<SalenetCar> carList = new ArrayList<>();
            carList = carMapper.selectByUserId(userId);
            System.out.println("当前购物车数据为"+carList);
            //添加信息到map集合
            carMap.put(userId,carList);
        }
    }


    /**
     * 更新数据库数据
     * 三十分钟一次更新数据库数据
     */
    @Scheduled(cron = "0 30 0 ? * *")
    public void updateSQL(){
        for(Map.Entry<Integer,List<SalenetCar>> map : carMap.entrySet()){
            List<SalenetCar> carList = map.getValue();
            for(SalenetCar car : carList){
                //对数据进行更新
                carMapper.updateByPrimaryKeySelective(car);
            }
        }
        //进行数据的加载
        load();
    }

    /**
     * 加载数据
     */
    public void load(){
        Map<Integer, List<SalenetCar>> newCarMap = new HashMap<>();
        //给map集合添加数据
        //先获取所有的用户
        List<Integer> userIdList = userMapper.selectAllUserId();
        //根据用户id获取对应用户在购物车中的数据
        for(Integer userId : userIdList){
            //循环获取数据然后添加到map中
            List<SalenetCar> carList = new ArrayList<>();
            carList = carMapper.selectByUserId(userId);
            //添加信息到map集合
            newCarMap.put(userId,carList);
        }
        carMap = newCarMap ;
    }
}
